package com.fc.push.handler.pub.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.fc.commons.security.MD5Util;
import com.fc.persistence.cache.ConstKey;
import com.fc.persistence.cache.redis.SharedJedisFacade;
import com.fc.push.GlobalServerConst;
import com.fc.push.db.TranscationFacade;
import com.fc.push.db.entities.IMessage;

/**
 * 公共方法
 * @author dc
 * @since 2015-12-1
 */
@Component
public class GlobalService {
	
	public GlobalService(){
		
	}
	/**
	 * 注册token/clientid到对应应用的Tag下面
	 * @param keySource
	 * @param appkey
	 * @param tag
	 * @param target
	 */
	public void registerInTag(String keySource,String appkey,Object tag,String target){
		String key = assKeyByAppkeyAndTag(appkey, keySource, tag);
		SharedJedisFacade.saddProxy(key, target);
	}
	
	/**
	 * 注册token/clientid到对应应用的全局Tag下面
	 * @param platform
	 * @param appkey
	 * @param target
	 */
	public void registerGlobalInTag(String platform,String appkey,String target){
		String key = null;
		if(platform.equals(GlobalServerConst.ANDROID)){
			key = assKeyByAppkeyAndTag(appkey, ConstKey.AN_APP_TAG_SET_IDS, "MESSAGE");
		}else if(platform.equals(GlobalServerConst.IOS)){
			key = assKeyByAppkeyAndTag(appkey, ConstKey.IOS_APP_TAG_SET_TOKENS, "MESSAGE");
		}else if(platform.equals(GlobalServerConst.WEB)){
			key = assKeyByAppkeyAndTag(appkey, ConstKey.WEB_APP_TAG_SET_IDS, "MESSAGE");
		}
		SharedJedisFacade.saddProxy(key, target);
	}
	
	/**
	 * 生成Redis中的Key
	 * @param appkey
	 * @param keySource
	 * @param tag
	 * @return
	 */
	public String assKeyByAppkeyAndTag(String appkey,String keySource,Object tag){
		String key = keySource.replaceFirst("APP", appkey);
		key = key.replaceFirst("TAG", tag.toString().toUpperCase());
		return key;
	}
	
	/**
	 * 过滤掉未注册的client,并将过滤掉的结果返回
	 * @param source
	 * @param appkey
	 * @return
	 */
	public List<Object> filterUnregisteredIDWhenPushedByID(List<Object> source, String appkey) {
		List<Object> result = new ArrayList<Object>();
		List<Object> temp = new ArrayList<>(source);
		for (Object object : temp) {
			String clientid = assClientId(appkey, object.toString());
			if (!SharedJedisFacade.sismemberProxy(appkey, clientid)) {
				result.add(object);
				source.remove(object);
			}
		}
		return result;
	}
	
	/**
	 * 生成客户端推送id
	 * @param appkey
	 * @param source Android为device_id,IOS为token
	 * @return
	 */
	public String assClientId(String appkey, String source) {
		return MD5Util.Instance.getInstance().md5TO23Bit(appkey + source);
	}
	
	/**
	 * 设置消息记录的状态码，并保存
	 * @param iMessage
	 * @param rCode
	 */
	public void setRCodeAndSave(IMessage iMessage, int rCode) {
		iMessage.setRcode(rCode);
		TranscationFacade.getInstance().transcation().save(iMessage);
	}
}
